package com.cdsz.boot.common.interceptor;

import com.cdsz.boot.common.utils.TraceIdUtils;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 注入日志需要变量 拦截器
 * @author gongli
 * @date 2024/6/6 16:44
 */
@Slf4j
public class MDCInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String traceId = TraceIdUtils.getTraceId();
        LoginUser loginUser = (LoginUser) Optional.ofNullable(SecurityUtils.getSubject())
                .flatMap(subject -> Optional.ofNullable(subject.getPrincipal()))
                .orElse(new LoginUser());
        String username = Strings.nullToEmpty(loginUser.getUsername());
        log.info("request user: {} url: {} traceId: {}", username, request.getRequestURI(), traceId);
        MDC.put("traceId", traceId);
        MDC.put("username", loginUser.getUsername());
        return true;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {
        response.setHeader("x-trace-id", TraceIdUtils.getTraceId());
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        MDC.remove("traceId");
    }
}
